package ide.ccf.ccproject.common;

import ide.ccf.ccproject.CCFNature;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.util.Locale;
import java.util.Vector;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具类
 *
 */
public class Utils 
{
	public final static int PATH_TYPE_BIN = 0;
	public final static int PATH_TYPE_INCLUDE = PATH_TYPE_BIN + 1;
	
	/**
	 * 获取QMAKESPEC
	 * @param dir
	 * @return
	 */
	public static String getMakeSpec(String dir) 
	{
		try 
		{
			Path qmakecash = new Path(dir + "/.qmake.cache");
			BufferedReader in = new BufferedReader(new FileReader(qmakecash.toOSString()));
			
			while (true) 
			{
				String line = in.readLine();
				
				if (line == null)
					break;
				
				if (line.startsWith("QMAKESPEC")) 
				{
					String [] args = line.split("=");
					
					if (args.length == 2) 
					{
						line = args[1].trim();
						line = line.replace('\\', '/');
						int lastindex = line.lastIndexOf('/');
						
						if (lastindex == -1)
							return line.trim();
						
						return line.substring(lastindex + 1).trim();
					}
				}
			}
		} 
		catch (IOException e) 
		{

		}
		return null;
	}
	
	/**
	 * 获取make命令
	 * @param mkspec
	 * @return
	 */
	public static String getMakeCommand(String mkspec) 
	{
		if (mkspec != null) 
		{
			if (mkspec.endsWith("win32-g++")) 
			{
				return "mingw32-make";
			} 
			else if(mkspec.indexOf("win32") > -1) 
			{
				return "nmake";
			}
		}
		return "make";		
	}
	
	/**
	 * 删除文件名
	 * @param path
	 * @return
	 */
	public static IPath removeFileName(IPath path) 
	{
		if (path == null)
			return null;
		
		if (path.hasTrailingSeparator())
			return path;
		
		return path.removeLastSegments(1);
	}
	
	/**
	 * 获取文件名
	 * @param path
	 * @param noextension
	 * @return
	 */
	public static String getFileName(IPath path, boolean noextension) 
	{
		if (path == null)
			return null;
		
		if (path.hasTrailingSeparator())
			return "";
		
		if (noextension)
			path = path.removeFileExtension();
		
		return path.lastSegment();
	}
	
	/**
	 * 获取规范路径
	 * @param path
	 * @return
	 */
	public static IPath getCanonicalPath(IPath path)
	{
		IPath result = new Path("");
		
		for (int i = 0; i < path.segmentCount(); i++) 
		{
			String segment = path.segment(i);
			if (segment.equals("."))
			{

			} 
			else if (segment.equals("..") && result.segmentCount() > 0) 
			{
				result = result.removeLastSegments(1);
			} 
			else 
			{	
				result = result.append(segment+"/");
			}
		}
		if (!path.hasTrailingSeparator())
			result = result.removeTrailingSeparator();
		
		if (path.isAbsolute())
			result = result.makeAbsolute();
		
		return result;
	}
	
	/**
	 * 相对路径
	 * @param path
	 * @param base
	 * @return
	 */
	public static IPath makeRelative(IPath path, IPath base)
	{
		IPath dir = getCanonicalPath(path);
		IPath baseDir = getCanonicalPath(base);
		
		if (!dir.hasTrailingSeparator())
			dir = dir.removeLastSegments(1);
		
		if (!baseDir.hasTrailingSeparator())
			baseDir = baseDir.removeLastSegments(1);
		
		int common = dir.matchingFirstSegments(baseDir);
		dir = dir.removeFirstSegments(common);
		IPath relative = new Path("");
		
		for (int i = 0; i < baseDir.segmentCount()-common; i++) 
			relative = relative.append("../");
		
		relative = relative.append(dir);
		relative = relative.append(getFileName(path, false));
		
		return relative;
	}
	
	/**
	 * 是否窗体设计文件
	 * @param filename
	 * @return
	 */
	public static boolean isFormFile(String filename) 
	{
		return filename.toLowerCase(Locale.US).endsWith(".ui");
	}
	
	/**
	 * 是否资源文件
	 * @param filename
	 * @return
	 */
	public static boolean isResourceFile(String filename) 
	{
		return filename.toLowerCase(Locale.US).endsWith(".qrc");
	}
	
	/**
	 * 是否生成的头文件
	 * @param filename
	 * @return
	 */
	public static boolean isGeneratedHeaderFile(String filename) 
	{
		return filename.toLowerCase(Locale.US).startsWith("ui_");
	}
	
	/**
	 * 是否生成的源文件
	 * @param filename
	 * @return
	 */
	public static boolean isGeneratedSourceFile(String filename) 
	{
		return filename.toLowerCase(Locale.US).startsWith("qrc_") || filename.toLowerCase(Locale.US).startsWith("moc_");
	}
	
	/**
	 * 查找项目文件
	 * @param pro
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static IPath findProFile(IProject pro) 
	{
		ProjectVisitor visitor = new ProjectVisitor();
		Vector result = visitor.findFiles(pro, "pro");
		
		if (result.size() <= 0)
			return null;
			
		IPath path = ((IResource)result.get(0)).getLocation();
		
		for (int i = 0; i < result.size(); i++)
			if (((IResource)result.get(i)).getProjectRelativePath().segmentCount() == 1)
				path = ((IResource)result.get(i)).getLocation();
		
		return path;			
	}

	/**
	 * 构建路径
	 * @param path
	 * @param prepend
	 * @param remove
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String createPath(String path, String prepend, String remove) 
	{
		Vector result = new Vector();
		result.add(prepend);
		
		if (remove != null)
			result.add(remove);
		
		// 系统环境
		result.add("${env_var:PATH}");
		
		String splitchar = ";";
		
		if (!Platform.getOS().equals(Platform.OS_WIN32))
			splitchar = ":";
		
		if (path != null) 
		{
			String[] pathlist = path.split(splitchar);
			
			for (int i = 0; i < pathlist.length; ++i) 
			{
				if (!result.contains(pathlist[i]))
					result.add(pathlist[i]);
			}
		}
		
		if (remove != null)
			result.remove(remove);
		
		path = prepend;
		
		for (int i = 1; i < result.size(); ++i) 
		{
			path += splitchar + (String)result.get(i);
		}
		
		return path;
	}
	
	/**
	 * 获取CCF工程
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static IProject[] getProjects() 
	{
		IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
		Vector projects = new Vector();
		
		for (int i = 0; i < allProjects.length; ++i) 
		{
			try 
			{
				if (allProjects[i].hasNature(CCFNature.NATURE_ID))//TODO mencius
					projects.add(allProjects[i]);
			} 
			catch (CoreException ex) 
			{
				
			}
		}
		IProject[] result = new IProject[projects.size()];
		
		for (int i = 0; i < result.length; ++i)
			result[i] = (IProject)projects.elementAt(i);
		
		return result;
	}
	
	/**
	 * 获取qmake可执行文件名称
	 * @return
	 */
	public static String getQmakeExecutableName() 
	{
		return System.getProperty("os.name").indexOf("Windows") == 0 ? "qmake.exe" : "qmake-qt4";
	}
	
	/**
	 * 获取CCF路径最后目录
	 * @param pathType
	 * @return
	 */
	public static String getCCFPathLastSegment(int pathType) 
	{
		return pathType == PATH_TYPE_BIN ? "bin" : "include";
	}

	/**
	 * 是否合法的CCF路径
	 * @param path
	 * @param pathType
	 * @return
	 */
	public static boolean isValidCCFPath(String path, int pathType) 
	{
		String subElement = pathType == PATH_TYPE_BIN ? getQmakeExecutableName() : "QtCore";
		boolean subElementMustBeDirectory = pathType == PATH_TYPE_INCLUDE;
		Path subElementPath = new Path(path);
		String subElementOSString = subElementPath.append(subElement).toOSString();
		
		File subElementFile = new File(subElementOSString);
		return subElementFile.exists() && (subElementFile.isDirectory() == subElementMustBeDirectory);
	}
	
	/**
	 * 获取同属CCF路径
	 * @param sourcePath
	 * @param sourceType
	 * @param targetType
	 * @return
	 */
	public static String getSiblingCCFPath(String sourcePath, int sourceType, int targetType) 
	{
		String result = "";
		
		if (isValidCCFPath(sourcePath, sourceType)) 
		{
			Path path = new Path(new Path(sourcePath).removeLastSegments(1).toOSString());
			String targetPathOSString = path.append(getCCFPathLastSegment(targetType)).toOSString();
			
			if (isValidCCFPath(targetPathOSString, targetType))
				result = targetPathOSString;
		}
		return result;
	}
	
	/**
	 * 在CCF路径下获取CCF路径
	 * @param path
	 * @param subPathType
	 * @return
	 */
	public static String getCCFSubPathUnderCCFPath(String path, int subPathType) 
	{
		String result = "";
		
		if (new File(path).exists()) 
		{
			Path subPath = new Path(new Path(path).append(getCCFPathLastSegment(subPathType)).toOSString());
			String subPathOSString = subPath.toOSString();
			
			if (isValidCCFPath(subPathOSString, subPathType))
				result = subPathOSString;
		}
		return result;
	}
	
	/**
	 * 是否CCF项目
	 * @param project
	 * @return
	 */
	public static boolean isCCFProject(IProject project) 
	{
		if (project == null)
			return false;
		try 
		{
			return project.hasNature(CCFNature.NATURE_ID); //TODO mencius
		} 
		catch (CoreException e) 
		{
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 获取编辑器打开文件所属的CCF项目
	 * @param input
	 * @return
	 */
	public static IProject projectOfEditorInput(IEditorInput input) 
	{
		if (input != null && input instanceof IFileEditorInput) 
		{
			IResource resource = ((IFileEditorInput)input).getFile();
			IProject project = resource.getProject();
			
			if (project != null && isCCFProject(project)) 
			{
				return project;
			}
		}
		return null;
	}
	
	/**
	 * 获取当前编辑器CCF项目
	 * 如果焦点在任何编辑器外，则返回null。
	 * 如果当前编辑器项目为CCF项目，则返回该项目，否则，也返回null。
	 * @return
	 */
	public static IProject projectOfActiveEditor() 
	{
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IEditorPart epart = page.getActiveEditor();
		IWorkbenchPart wpart = page.getActivePart();
		
		if (epart != null && epart.equals(wpart)) 
		{
			IEditorInput input = epart.getEditorInput();
			return projectOfEditorInput(input);
		}
	    return null;
	}
	
	/**
	 * 判断是否存在文件
	 * @param path
	 * @return
	 */
	public static boolean isExistFile(String path)
	{
		File file=new File(path);    
		return file.exists() ? true : false;
	}
	
	/**
	 * 判断是否存在文件夹
	 * @param path
	 */
	 public static boolean isExist(String path) {
		  File file = new File(path);
		  //判断文件夹是否存在,如果不存在则创建文件夹
		  if (!file.exists()) {
		  // file.mkdir();
			  return false;
		  }
		  return true;
		 }
	
	 /**
	  * 从ini配置文件中读取变量的值
	  *
	  * @param file
	  *            配置文件的路径
	  * @param section
	  *            要获取的变量所在段名称
	  * @param variable
	  *            要获取的变量名称
	  * @param defaultValue
	  *            变量名称不存在时的默认值
	  * @return 变量的值
	  * @throws IOException
	  *             抛出文件操作可能出现的io异常
	  */
	 public static String getProfileString(String file, String section, String variable, String defaultValue) throws IOException {
	  String strLine, value = "";
	  BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
	  boolean isInSection = false;
	  try {
	   while ((strLine = bufferedReader.readLine()) != null) {
	    strLine = strLine.trim();
	    strLine = strLine.split("[;]")[0];
	    Pattern p;
	    Matcher m;
	    p = Pattern.compile("//[//s*.*//s*//]");
	    m = p.matcher((strLine));
	    if (m.matches()) {
	     p = Pattern.compile("//[//s*" + section + "//s*//]");
	     m = p.matcher(strLine);
	     if (m.matches()) {
	      isInSection = true;
	     } else {
	      isInSection = false;
	     }
	    }
	    if (isInSection == true) {
	     strLine = strLine.trim();
	     String[] strArray = strLine.split("=");
	     if (strArray.length == 1) {
	      value = strArray[0].trim();
	      if (value.equalsIgnoreCase(variable)) {
	       value = "";
	       return value;
	      }
	     } else if (strArray.length == 2) {
	      value = strArray[0].trim();
	      if (value.equalsIgnoreCase(variable)) {
	       value = strArray[1].trim();
	       return value;
	      }
	     } else if (strArray.length > 2) {
	      value = strArray[0].trim();
	      if (value.equalsIgnoreCase(variable)) {
	       value = strLine.substring(strLine.indexOf("=") + 1).trim();
	       return value;
	      }
	     }
	    }
	   }
	  } finally {
	   bufferedReader.close();
	  }
	  return defaultValue;
	 }

	 /**
	  * 修改ini配置文件中变量的值
	  *
	  * @param file
	  *            配置文件的路径
	  * @param variable
	  *            要修改的变量名称
	  * @param value
	  *            变量的新值
	  * @throws IOException
	  *             抛出文件操作可能出现的io异常
	  */
	 public static boolean setProfileString(String file, String variable, String value) throws IOException {
	  String fileContent, allLine, strLine, newLine, remarkStr;
	  String getValue;
	  BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
	  fileContent = "";
	  try {
		   while ((allLine = bufferedReader.readLine()) != null) {
		    allLine = allLine.trim();
		    //System.out.println("allLine："+ allLine);
		    if (allLine.split("[;]").length > 1)
		    	remarkStr = ";" + allLine.split(";")[1];
		    else
		    	remarkStr = "";
		    //System.out.println("remarkStr：" + remarkStr);
		    strLine = allLine.split("#")[0];
		    //System.out.println("strLine：" + strLine);

		     strLine = strLine.trim();
		     String[] strArray = strLine.split("\\=");
		     getValue = strArray[0].trim();
		     //System.out.println("getValue："+ getValue);
		     if (getValue.equalsIgnoreCase(variable)) {
		      newLine = getValue + " = " + value/* + " " + remarkStr*/;
		      fileContent += newLine + "\r\n";
		      //System.out.println("fileContent-1:"+ fileContent);
		      while ((allLine = bufferedReader.readLine()) != null) {
		       fileContent += allLine + "\r\n";
		       //System.out.println("fileContent-2:"+ fileContent);
		      }
		      bufferedReader.close();
		      BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false));
		      bufferedWriter.write(fileContent);
		      bufferedWriter.flush();
		      bufferedWriter.close();	
		      return true;
		     }
		    fileContent += allLine + "\r\n";
		    //System.out.println("fileContent-3:"+ fileContent);
		   }
	  } catch (IOException ex) {
	   throw ex;
	  } finally {
	   bufferedReader.close();
	  }
	  return false;
	 }

	 /**
	  * 生成CPK文件夹
	  * @param path
	  */
	public static void generalCPK(String path) {
		File file = new File(path + "/CPK");
		//如果文件夹不存在则创建
		if(!file.exists() && !file.isDirectory())
			file.mkdir();
	}
	
	 /**
     * 执行shell命令
     *String[] cmd = { "sh", "-c", "lsmod |grep linuxVmux" }或者
     *String[] cmd = { "sh", "-c", "./load_driver.sh" }
     *int tp = 1 返回执行结果  非1 返回命令执行后的输出
     */
  public static String runCommand(String[] cmd,int tp){
     StringBuffer buf = new StringBuffer(1000);
     String rt="-1";
  try {
   Process pos = Runtime.getRuntime().exec(cmd);
   pos.waitFor();
   if(tp==1){
    if(pos.exitValue()==0){
     rt="1";
    }
   }else{
    InputStreamReader ir = new InputStreamReader(pos.getInputStream());
    LineNumberReader input = new LineNumberReader(ir);
    String ln="";
    while ((ln =input.readLine()) != null) {
        buf.append(ln+"<br>");
    }
    rt = buf.toString();
    input.close();
    ir.close();
   }
  } catch (java.io.IOException e) {
   rt=e.toString();
  }catch (Exception e) {
   rt=e.toString();
  }
     return rt;
    }
  
    /**
     * 执行简单命令
    * String cmd="ls"
     *int tp = 1 返回执行结果  非1 返回命令执行后的输出
     */
  public static String runCommand(String cmd,int tp){
      StringBuffer buf = new StringBuffer(1000);
      String rt="-1";
	  try {
		   Process pos = Runtime.getRuntime().exec(cmd);
		   pos.waitFor();
		   if(tp==1){
		    if(pos.exitValue()==0){
		     rt="1";
		    }
		   }else{
		    InputStreamReader ir = new InputStreamReader(pos.getInputStream());
		    LineNumberReader input = new LineNumberReader(ir);
		    String ln="";
		    while ((ln =input.readLine()) != null) {
		        buf.append(ln+"\r\n");
		    }
		    rt = buf.toString();
		    input.close();
		    ir.close();
		   }
	  } catch (java.io.IOException e) {
	   rt=e.toString();
	  }catch (Exception e) {
	   rt=e.toString();
	  }
     return rt;
    }
  
  /**
   * A方法追加文件：使用RandomAccessFile
   */
  public static void appendMethodA(String fileName, String content) {
      try {
          // 打开一个随机访问文件流，按读写方式
          RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
          // 文件长度，字节数
          long fileLength = randomFile.length();
          //将写文件指针移到文件尾。
          randomFile.seek(fileLength);
          randomFile.writeBytes(content);
          randomFile.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

  /**
   * B方法追加文件：使用FileWriter
   */
  public static void appendMethodB(String fileName, String content) {
      try {
          //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
          FileWriter writer = new FileWriter(fileName, true);
          writer.write(content);
          writer.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
  public static String readToString(File file){
	  Long filelength = file.length();
	  byte[] filecontent = new byte[filelength.intValue()];
	  try{
		  FileInputStream in = new FileInputStream(file);
		  in.read(filecontent);
		  in.close();
	  }catch(FileNotFoundException e){
		  e.printStackTrace();
	  } catch(IOException e){
		  e.printStackTrace();
	  }
	  return new String(filecontent);
  }
  
  @SuppressWarnings("resource")
public static boolean isExistFlag(String path, String ch)
  {
	    BufferedReader bis = null;
	    String s = null;	
		try
		   { 
		     bis = new BufferedReader(new FileReader(path));
		      while(null != (s = bis.readLine()))
		      {
		    	  if(s.trim().equals(ch))
		    		  return true;
		   	  }
		    bis.close();
		    s = null;
	    }
	   catch(FileNotFoundException e)
	{
		System.out.println("未找到文件\n");
	}
	catch(IOException ee)
	{
		
	}
		return false;
  }
  
  public static List<String> readFile(String filePath, String strStart, String strEnd)throws IOException {
	  //File file = new File(filePath);
	  BufferedReader reader = null;
	  int lineStart = 0;
	  int lineEnd = 0;
	  int line = 0;
	  List<String> list = new ArrayList<String>();
	  reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
	  String text = reader.readLine();
	  while (text != null) {
	  line ++;
	  if(text.trim().equals(strStart))
	  lineStart = line;
	  if(text.trim().equals(strEnd))
	  lineEnd = line;
	  text = reader.readLine();
	  }
	  reader.close();
	  line = 0;
	  reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
	  text = reader.readLine();
	  while (text != null) {
	  line++;
	  if(line < lineStart ||
	  line > lineEnd)
	  {
	  list.add(text + "\r\n");
	  }
	  text = reader.readLine();
	  }
	  return list;
	  } 

  public static void writeFile(String filePath, List<String> list)
		  throws IOException {
		  File file = new File(filePath);
		  if (!file.exists()) {
		  file.createNewFile();
		  }
		  FileOutputStream outputStream = new FileOutputStream(file);
		  for (String s : list) {
		  outputStream.write(s.getBytes());
		  }
		  outputStream.close();
		  } 
  
  /**
   * 
   * @param s 源文件
   * @param t 复制到的新文件
   */
  public static void fileChannelCopy(File s, File t) {
      FileInputStream fi = null;
      FileOutputStream fo = null;
      FileChannel in = null;
      FileChannel out = null;
      try {
          fi = new FileInputStream(s);
          fo = new FileOutputStream(t);
          in = fi.getChannel();//得到对应的文件通道
          out = fo.getChannel();//得到对应的文件通道
          in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          try {
              fi.close();
              in.close();
              fo.close();
              out.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  
  /** 
  * 复制单个文件 
  * @param oldPath String 原文件路径 如：c:/fqf.txt 
  * @param newPath String 复制后路径 如：f:/fqf.txt 
  * @return boolean 
  */ 
  public static void copyFile(String oldPath, String newPath) { 
  try { 
	  int bytesum = 0; 
	  int byteread = 0; 
	  File oldfile = new File(oldPath); 
	  if (oldfile.exists()) { //文件存在时 
		  InputStream inStream = new FileInputStream(oldPath); //读入原文件 
		  FileOutputStream fs = new FileOutputStream(newPath); 
		  byte[] buffer = new byte[1444]; 
		  int length; 
		  while ( (byteread = inStream.read(buffer)) != -1) { 
			  bytesum += byteread; //字节数 文件大小 
			  System.out.println(bytesum); 
			  fs.write(buffer, 0, byteread); 
	  } 
	  inStream.close(); 
	  } 
	  } 
  catch (Exception e) { 
	  System.out.println("复制单个文件操作出错"); 
	  e.printStackTrace(); 
  } 
  } 
  
	public static boolean copyFile(String srcPath, String destDir, boolean overwriteExistFile) {
		// TODO 自动生成的方法存根
		boolean flag = false;

        File srcFile = new File(srcPath);
        if (!srcFile.exists() || !srcFile.isFile()) { // 源文件不存在
            return false;
        }

        //获取待复制文件的文件名
        String fileName = srcFile.getName();
        String destPath = destDir + File.separator +fileName;
        File destFile = new File(destPath);
        if (destFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) { // 源文件路径和目标文件路径重复
            return false;
        }
        if(destFile.exists() && !overwriteExistFile) {    // 目标目录下已有同名文件且不允许覆盖
            return false;
        }

        File destFileDir = new File(destDir);
        if(!destFileDir.exists() && !destFileDir.mkdirs()) { // 目录不存在并且创建目录失败直接返回
         return false;
        }

        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fos.flush();
            fis.close();
            fos.close();

            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return flag;
	}

  /** 
  * 复制整个文件夹内容 
  * @param oldPath String 原文件路径 如：c:/fqf 
  * @param newPath String 复制后路径 如：f:/fqf/ff 
  * @return boolean 
  */ 
  public static void copyFolder(String oldPath, String newPath) { 

	  try { 
		  (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 
		  File a=new File(oldPath); 
		  String[] file=a.list(); 
		  File temp=null; 
		  for (int i = 0; i < file.length; i++) { 
		  if(oldPath.endsWith(File.separator)){ 
		  temp=new File(oldPath+file[i]); 
	  } 
	  else{ 
		  temp=new File(oldPath+File.separator+file[i]); 
	  } 
	
	  if(temp.isFile()){ 
		  FileInputStream input = new FileInputStream(temp); 
		  FileOutputStream output = new FileOutputStream(newPath + "/" + 
		  (temp.getName()).toString()); 
		  byte[] b = new byte[1024 * 5]; 
		  int len; 
		  while ( (len = input.read(b)) != -1) { 
		  output.write(b, 0, len); 
		  } 
		  output.flush(); 
		  output.close(); 
		  input.close(); 
	  } 
	  if(temp.isDirectory()){//如果是子文件夹 
		  copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
	  } 
	  } 
	  } 
	  catch (Exception e) { 
		  System.out.println("复制整个文件夹内容操作出错"); 
		  e.printStackTrace(); 
	  } 
  }
  
  public static boolean copyDirectory(String srcPath, String destDir, boolean overwriteExistDir) {
      boolean flag = false;
      File srcFile = new File(srcPath);
      if (!srcFile.exists() || !srcFile.isDirectory()) { // 源文件夹不存在
          return false;
      }

      //获得待复制的文件夹的名字，比如待复制的文件夹为"E:\\dir\\"则获取的名字为"dir"
      String dirName = srcFile.getName();

      //目标文件夹的完整路径
      String destDirPath = destDir + File.separator + dirName + File.separator;
      File destDirFile = new File(destDirPath);
      if(destDirFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) {
       return false;
      }
      if(destDirFile.exists() && destDirFile.isDirectory() && !overwriteExistDir) {    // 目标位置有一个同名文件夹且不允许覆盖同名文件夹，则直接返回false
          return false;
      }

      if(!destDirFile.exists() && !destDirFile.mkdirs()) {  // 如果目标目录不存在并且创建目录失败
       return false;
      }

      File[] fileList = srcFile.listFiles();    //获取源文件夹下的子文件和子文件夹
      if(fileList.length==0) {    // 如果源文件夹为空目录则直接设置flag为true，这一步非常隐蔽，debug了很久
          flag = true;
      }
      else {
          for(File temp: fileList) {
              if(temp.isFile()) {    // 文件
                  flag = Utils.copyFile(temp.getAbsolutePath(), destDirPath, overwriteExistDir);     // 递归复制时也继承覆盖属性
              }
              else if(temp.isDirectory()) {    // 文件夹
                  flag = copyDirectory(temp.getAbsolutePath(), destDirPath, overwriteExistDir);   // 递归复制时也继承覆盖属性
              }

              if(!flag) {
                  break;
              }
          }
      }

      return flag;
}

  
	 /**
   * 删除文件或文件夹
   * @param path
   *            待删除的文件的绝对路径
   * @return boolean
   */
  public static boolean deleteFile(String path) {
      boolean flag = false;
     
      File file = new File(path);
      if (!file.exists()) { // 文件不存在直接返回
          return flag;
      }

      flag = file.delete();

      return flag;
  }
}